from common.recordlog import logs
import pymysql
from conf.operactionconfig import OperactionConfig
import json

op = OperactionConfig()

class MysqlConnection(object):
    def __init__(self):
        """
        初始化方法，用于建立数据库连接。
        
        Args:
            无
        
        Returns:
            无返回值，建立数据库连接并初始化实例变量self.conn和self.cursor。
        
        Raises:
            Exception: 当连接数据库失败时，抛出异常。
        
        """
        try:
            mysql_key = {
                'host': op.get_section_for_data('MYSQL', 'host'),
                'user': op.get_section_for_data('MYSQL', 'user'),
                'password': op.get_section_for_data('MYSQL', 'password'),
                'database': op.get_section_for_data('MYSQL', 'database'),
                'port': int(op.get_section_for_data('MYSQL', 'port'))
            }
            self.conn = pymysql.connect(**mysql_key, charset='utf8',cursorclass=pymysql.cursors.DictCursor)
            self.cursor = self.conn.cursor()
            logs.info(f'连接数据库成功信息是:{json.dumps(mysql_key)}')
        except Exception as e:
            logs.error(e)

    def query(self, sql):
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as e:
            logs.error(f'Query failed: {e}')
            return None
        finally:
            self.cursor.close()
            self.conn.close()

if __name__ == '__main__':
    db = MysqlConnection()
    print(db.query('SELECT * FROM users'))
